import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

# 加载CSV文件
sales_data_path = 'D:\project-2024-AA\联合.csv'
sales_data = pd.read_csv(sales_data_path)

# 转换fhjl_time为datetime格式
sales_data['fhjl_time'] = pd.to_datetime(sales_data['fhjl_time'])

# 过滤水泥和矿粉数据
cement_data = sales_data[sales_data['hplx'] == '水泥']
slag_powder_data = sales_data[sales_data['hplx'] == '矿粉']

# 按月汇总数据
cement_data_monthly = cement_data.resample('M', on='fhjl_time')['fhdw'].sum()
slag_powder_data_monthly = slag_powder_data.resample('M', on='fhjl_time')['fhdw'].sum()


# 创建特征
def create_features(data, label=None):
    data = data.reset_index()
    data['month'] = data['fhjl_time'].dt.month
    data['year'] = data['fhjl_time'].dt.year
    X = data[['month', 'year']]
    if label:
        y = data[label]
        return X, y
    return X


# 创建训练和测试数据集
X_cement, y_cement = create_features(cement_data_monthly.to_frame(), 'fhdw')
X_slag, y_slag = create_features(slag_powder_data_monthly.to_frame(), 'fhdw')


# 使用随机森林模型进行预测
def train_and_predict(X, y, steps=12):
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
    model = RandomForestRegressor(n_estimators=100)
    model.fit(X_train, y_train)

    # 预测未来的销量
    future_months = [(X['month'].max() + i) % 12 for i in range(1, steps + 1)]
    future_years = [X['year'].max() + (X['month'].max() + i) // 12 for i in range(1, steps + 1)]
    future_X = pd.DataFrame({'month': future_months, 'year': future_years})

    forecast = model.predict(future_X)
    return model, forecast, y_test


# 预测未来12个月的数据
steps = 12
cement_model, cement_forecast, cement_y_test = train_and_predict(X_cement, y_cement, steps)
slag_model, slag_forecast, slag_y_test = train_and_predict(X_slag, y_slag, steps)

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决坐标轴负号显示问题

# 绘制水泥销量数据及预测
plt.figure(figsize=(14, 7))
plt.plot(cement_data_monthly.index, cement_data_monthly.values, label='历史水泥销量')
future_dates = pd.date_range(cement_data_monthly.index[-1], periods=steps + 1, freq='M')[1:]
plt.plot(future_dates, cement_forecast, label='预测水泥销量', color='red', linestyle='--')
plt.title('2025年水泥销量预测')
plt.xlabel('日期')
plt.ylabel('销量 (吨)')
plt.legend()
plt.grid(True)
plt.show()

# 绘制矿粉销量数据及预测
plt.figure(figsize=(14, 7))
plt.plot(slag_powder_data_monthly.index, slag_powder_data_monthly.values, label='历史矿粉销量')
future_dates = pd.date_range(slag_powder_data_monthly.index[-1], periods=steps + 1, freq='M')[1:]
plt.plot(future_dates, slag_forecast, label='预测矿粉销量', color='red', linestyle='--')
plt.title('2025年矿粉销量预测')
plt.xlabel('日期')
plt.ylabel('销量 (吨)')
plt.legend()
plt.grid(True)
plt.show()








